<template>
  <view class="bill-summary-form">
    <scroll-view class="form-container" scroll-y="true">
      <uni-card>
        <view class="form-title">{{ formTitle }}</view>
        
        <uni-forms ref="formRef" :model="formData" :rules="rules" label-width="110px" label-position="left">
          <!-- 公司名称 -->
          <uni-forms-item label="公司名称" name="department" required>
            <view class="multi-select-container">
              <view class="selected-user-tag" v-show="formData.departmentName">
                <text>{{ formData.departmentName }}</text>
              </view>
              
              <view v-if="!readonly && !isApproval" class="add-user-btn" @click="openDepartmentPopup">
                <uni-icons type="plus" size="16"></uni-icons>
                <text>选择公司</text>
              </view>
              
              <uni-popup ref="departmentPopup" background-color="#fff" type="bottom">
                <view class="tree-box">
                  <view class="popup-header">
                    <text>选择公司</text>
                    <uni-icons type="close" size="20" @click="closeDepartmentPopup"></uni-icons>
                  </view>
                  
                  <view class="tree-box-top">
                    <DaTree
                      :data="enabledDeptOptions"
                      labelField="label"
                      valueField="id"
                      defaultExpandAll
                      :defaultCheckedKeys="formData.department"
                      @change="handleTreeChange" />
                  </view>
                  
                  <view class="tree-box-btn">
                    <view class="popup-actions">
                      <button class="btn primary" @click="closeDepartmentPopup">确定</button>
                    </view>
                  </view>
                </view>
              </uni-popup>
            </view>
          </uni-forms-item>

          <!-- 日期 -->
          <uni-forms-item label="日期" name="businessTripDate" required>
            <uni-datetime-picker
              v-model="formData.businessTripDate"
              type="date"
              :disabled="readonly || isApproval"
              placeholder="请选择日期"
            ></uni-datetime-picker>
          </uni-forms-item>

          <!-- 报销人 -->
          <uni-forms-item label="报销人" name="reimbursementUser" required>
            <uni-data-select
              v-model="formData.reimbursementUser"
              :localdata="reimbursementUserOptions"
              :clear="!readonly && !isApproval"
              :disabled="readonly || isApproval"
              placeholder="请选择报销人"
            ></uni-data-select>
          </uni-forms-item>

          <!-- 审核人 -->
          <uni-forms-item label="审核人" name="reviewUser" required>
            <uni-data-select
              v-model="formData.reviewUser"
              :localdata="reviewUserOptions"
              :clear="!readonly && !isApproval"
              :disabled="readonly || isApproval"
              placeholder="请选择审核人"
            ></uni-data-select>
          </uni-forms-item>

          <!-- 复核人 -->
          <uni-forms-item label="复核人" name="recheckUser">
            <uni-data-select
              v-model="formData.recheckUser"
              :localdata="recheckUserOptions"
              :clear="!readonly && !isApproval"
              :disabled="readonly || isApproval"
              placeholder="请选择复核人"
            ></uni-data-select>
          </uni-forms-item>

          <!-- 支付行及账户 -->
          <uni-forms-item label="支付行及账户" name="accountNo" required>
            <uni-data-select
              v-model="formData.accountNo"
              :localdata="bankOptions"
              :clear="!readonly && !isApproval"
              :disabled="readonly || isApproval"
              placeholder="请选择开户行"
              @change="handleBankChange"
            ></uni-data-select>
          </uni-forms-item>

          <!-- 汇总项目清单 -->
          <view class="section-title">汇总项目清单</view>
          <view class="summary-table">
            <view class="table-header">
              <text class="table-col">会计科目名称</text>
              <text class="table-col">项目</text>
              <text class="table-col">金额</text>
              <text class="table-col">用途</text>
            </view>
            
            <view class="table-row" v-for="(item, index) in projectTableData" :key="index">
              <view class="table-col">
                <uni-data-select
                  v-model="item.subjectName"
                  :localdata="costTypeOptions"
                  :disabled="readonly || isApproval"
                  placeholder="选择科目"
                  @change="handleSubjectChange(item, $event)"
                ></uni-data-select>
              </view>
              
              <view class="table-col">
                <uni-data-select
                  v-model="item.projectName"
                  :localdata="item.projectOptions || []"
                  :disabled="readonly || isApproval"
                  placeholder="选择项目"
                ></uni-data-select>
              </view>
              
              <view class="table-col">
                <uni-easyinput
                  v-model="amountTotal"
                  type="number"
                  :disabled="true"
                  placeholder="金额"
                ></uni-easyinput>
              </view>
              
              <view class="table-col">
                <uni-easyinput
                  v-model="item.remarks"
                  :disabled="readonly || isApproval"
                  placeholder="用途"
                ></uni-easyinput>
              </view>
            </view>
            
            <view class="table-footer">
              <text class="table-col">合计</text>
              <text class="table-col">{{ amountToChinese(amountTotal) }}</text>
              <text class="table-col">￥{{ amountTotal.toFixed(2) }}</text>
              <text class="table-col"></text>
            </view>
          </view>

          <!-- 报销金额清单 -->
          <view class="section-title">报销金额清单</view>
          <view class="summary-table">
            <view class="table-header">
              <text class="table-col">取得日期</text>
              <text class="table-col">名称</text>
              <text class="table-col">金额</text>
              <text class="table-col">张数</text>
              <text class="table-col">附件</text>
              <text class="table-col">备注</text>
              <text class="table-col" v-if="!readonly && !isApproval">操作</text>
            </view>
            
            <view class="table-row" v-for="(item, index) in amountTableData" :key="index">
              <view class="table-col">
                <uni-datetime-picker
                  v-model="item.obtainDate"
                  type="date"
                  :disabled="readonly || isApproval"
                  placeholder="选择日期"
                ></uni-datetime-picker>
              </view>
              
              <view class="table-col">
                <uni-easyinput
                  v-model="item.fileName"
                  :disabled="readonly || isApproval"
                  placeholder="名称"
                ></uni-easyinput>
              </view>
              
              <view class="table-col">
                <uni-easyinput
                  v-model="item.amount"
                  type="number"
                  :disabled="readonly || isApproval"
                  placeholder="金额"
                ></uni-easyinput>
              </view>
              
              <view class="table-col">
                <uni-easyinput
                  v-model="item.fileNum"
                  type="number"
                  :disabled="readonly || isApproval"
                  placeholder="张数"
                ></uni-easyinput>
              </view>
              
              <view class="table-col">
                <button 
                  class="btn small primary" 
                  @click="openFileListDialog(item, index)"
                  :disabled="readonly"
                >
                  附件
                </button>
              </view>
              
              <view class="table-col">
                <uni-easyinput
                  v-model="item.remarks"
                  :disabled="readonly || isApproval"
                  placeholder="备注"
                ></uni-easyinput>
              </view>
              
              <view class="table-col" v-if="!readonly && !isApproval">
                <uni-icons 
                  type="close" 
                  size="20" 
                  color="#f56c6c" 
                  @click="removeAmountRow(index)"
                  v-if="amountTableData.length > 1"
                ></uni-icons>
              </view>
            </view>
            
            <view class="table-footer">
              <text class="table-col">合计</text>
              <text class="table-col"></text>
              <text class="table-col">￥{{ amountTotal.toFixed(2) }}</text>
              <text class="table-col">{{ fileNumTotal }}</text>
              <text class="table-col"></text>
              <text class="table-col"></text>
              <text class="table-col" v-if="!readonly && !isApproval"></text>
            </view>
          </view>
          
          <view v-if="!readonly && !isApproval" class="table-actions">
            <button class="btn small primary" @click="addAmountRow">新增行</button>
          </view>

          <!-- 审核人审批 -->
					<template v-if="(isApproval && processStatusOpen === '0') || (processStatusOpen === '2' || processStatusOpen === '3')">
						<view class="section-title">审批意见</view>
						
						<uni-forms-item label="审批结果" name="reviewApprovalFlag" required>
						  <uni-data-checkbox
						    v-model="formData.reviewApprovalFlag"
						    :localdata="approvalOptions"
						    :disabled="readonly"
						  ></uni-data-checkbox>
						</uni-forms-item>
						
						<uni-forms-item label="审批意见" name="reviewUserNotes">
						  <uni-easyinput
						    type="textarea"
						    v-model="formData.reviewUserNotes"
						    :disabled="readonly"
						    placeholder="请输入审批意见"
						  ></uni-easyinput>
						</uni-forms-item>
					</template>
					
					<!-- 审核人签名回显 -->
					<template v-if="readonly && (processStatusOpen === '2') && signatureDataReview">
						<view class="signature-container">
							<view class="section-title">签名预览</view>
							<image :src="signatureDataReview" class="signature-image" mode="widthFix"></image>
						</view>
					</template>
					
					<!-- 复核人审批 -->
					<template v-if="(isApproval && processStatusOpen === '1') || ((processStatusOpen === '2' || processStatusOpen === '3') && formData.recheckApprovalFlag)">
						<view class="section-title">审批意见</view>
						
						<uni-forms-item label="复核结果" name="recheckApprovalFlag" required>
						  <uni-data-checkbox
						    v-model="formData.recheckApprovalFlag"
						    :localdata="approvalOptions"
						    :disabled="readonly"
						  ></uni-data-checkbox>
						</uni-forms-item>
						
						<uni-forms-item label="复核意见" name="recheckUserNotes">
						  <uni-easyinput
						    type="textarea"
						    v-model="formData.recheckUserNotes"
						    :disabled="readonly"
						    placeholder="请输入复核意见"
						  ></uni-easyinput>
						</uni-forms-item>
					</template>
					
					<!-- 复核人签名回显 -->
					<template v-if="readonly && (processStatusOpen === '2') && signatureDataRecheck">
						<view class="signature-container">
							<view class="section-title">签名预览</view>
							<image :src="signatureDataRecheck" class="signature-image" mode="widthFix"></image>
						</view>
					</template>

					<!-- 签名部分 -->
          <template v-if="isApproval">
						<!-- 审核人签字 -->
            <view class="signature-section" v-show="!readonly && processStatusOpen === '0' && formData.reviewApprovalFlag === '1'">
              <view class="section-title">审核人签字</view>
              <canvas 
                canvas-id="reviewUserSignaturePad" 
                class="signature-pad"
                @touchstart="onTouchStart"
                @touchmove="onTouchMove"
                @touchend="onTouchEnd"
              ></canvas>
              <view class="signature-actions">
                <button class="btn default" @click="clearSignature">清除</button>
                <button class="btn primary" @click="saveSignature">保存签名</button>
              </view>
            </view>
						
						<!-- 复核人签字 -->
						<view class="signature-section" v-show="!readonly && processStatusOpen === '1' && formData.recheckApprovalFlag === '1'">
						  <view class="section-title">复核人签字</view>
						  <canvas 
						    canvas-id="recheckUserSignaturePad" 
						    class="signature-pad"
						    @touchstart="onTouchStart"
						    @touchmove="onTouchMove"
						    @touchend="onTouchEnd"
						  ></canvas>
						  <view class="signature-actions">
						    <button class="btn default" @click="clearSignature">清除</button>
						    <button class="btn primary" @click="saveSignature">保存签名</button>
						  </view>
						</view>
          </template>
					
        </uni-forms>

        <!-- 操作按钮 -->
        <view class="form-actions" v-if="!readonly">
          <button class="btn default large" @click="handleClose">取消</button>
					<button class="btn primary large" @click="submitForm">提交</button>
        </view>
        
        <view class="form-actions" v-else>
          <button class="btn default large" @click="handleClose">关闭</button>
        </view>
      </uni-card>
    </scroll-view>

    <!-- 文件管理弹窗 -->
    <uni-popup ref="filePopup" type="bottom">
      <view class="file-popup">
        <view class="popup-header">
          <text>管理附件</text>
          <uni-icons type="close" size="20" @click="closeFilePopup"></uni-icons>
        </view>
        
        <view class="file-form">
          <uni-forms :model="currentRowFile" label-width="100px" label-position="top">
            <uni-forms-item label="文件批次号">
              <text>{{ currentRowFile.fileBatchNo }}</text>
            </uni-forms-item>
            
            <uni-forms-item label="文件列表">
              <view class="file-uploader">
                <uni-file-picker
                  v-model="currentRowFile.fileList"
                  fileMediatype="all"
                  limit="9"
                  :disabled="readonly"
                ></uni-file-picker>
              </view>
            </uni-forms-item>
          </uni-forms>
        </view>
        
        <view class="popup-actions">
          <button class="btn primary" @click="confirmFile">确定</button>
          <button class="btn default" @click="closeFilePopup">取消</button>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script setup>
import { ref, reactive, computed, onMounted, nextTick } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import DaTree from '@/components/da-tree/index.vue'
import { 
  billSummaryAdd,
  billSummaryEdit,
  billSummaryGet,
  billSummaryApproval
} from "@/api/documentApproval/billSummary"
import { deptTreeSelect, listUser } from "@/api/system/user"
import { listData } from "@/api/system/dict/data"
import { listDeposit } from '@/api/system/deposit'

// 响应式数据
const formData = reactive({
  id: null,
  department: null,
  departmentName: '',
  businessTripDate: '',
  reimbursementUser: null,
  reviewUser: null,
  recheckUser: null,
  bankName: '',
  accountNo: null,
  reportNum: 0,
  serialNumber: '',
  approvFlag: 'Y',
  reviewUserNotes: '',
  recheckUserNotes: '',
  reviewUserImg: '',
  recheckUserImg: ''
})

const projectTableData = reactive([
  { subjectName: '', projectName: '', totalAmount: 0, remarks: '' }
])

const amountTableData = reactive([
  { obtainDate: '', fileName: '', amount: 0, fileNum: 0, fileList: [], remarks: '', fileBatchNo: '' }
])

const currentRowFile = reactive({
  fileBatchNo: '',
  fileList: []
})

const currentRowFileIndex = ref(-1)
const signatureData = ref(null)
const isDrawing = ref(false)
const lastX = ref(0)
const lastY = ref(0)
const ctx = ref(null)

let reviewUserSignaturePad = ref(null)
let reviewUserSignature = null

let recheckUserSignaturePad = ref(null)
let recheckUserSignature = null

const signatureDataReview = ref(null);
const signatureDataRecheck = ref(null);

// 选项数据
const enabledDeptOptions = ref([])
const reimbursementUserOptions = ref([])
const reviewUserOptions = ref([])
const recheckUserOptions = ref([])
const bankOptions = ref([])
const costTypeOptions = ref([])
const approvalOptions = ref([
  { value: '1', text: '同意' },
  { value: '0', text: '不同意' }
])
const projectOptionsMap = ref({})

// 状态控制
const handle = ref('')
const isApproval = ref(false)
const readonly = ref(false)
const processStatusOpen = ref('0')

// 表单引用
const formRef = ref(null)
const filePopup = ref(null)
const departmentPopup = ref(null)

// 表单验证规则
const rules = reactive({
  department: {
    rules: [{ required: true, errorMessage: '请选择公司名称' }]
  },
  businessTripDate: {
    rules: [{ required: true, errorMessage: '请选择日期' }]
  },
  reimbursementUser: {
    rules: [{ required: true, errorMessage: '请选择报销人' }]
  },
  reviewUser: {
    rules: [{ required: true, errorMessage: '请选择审核人' }]
  },
  accountNo: {
    rules: [{ required: true, errorMessage: '请选择开户行' }]
  },
  approvFlag: {
    rules: [{ required: true, errorMessage: '请选择审批意见' }]
  }
})

// 计算属性
const formTitle = computed(() => {
  if (readonly.value) return '查看汇总清单'
  if (isApproval.value) return '汇总清单审批'
  return formData.id ? '编辑汇总清单' : '新增汇总清单'
})

const signatureTitle = computed(() => {
  return processStatusOpen.value === '0' ? '审核人' : '复核人'
})

const amountTotal = computed(() => {
  return amountTableData.reduce((sum, item) => {
    return sum + (Number(item.amount) || 0)
  }, 0)
})

const fileNumTotal = computed(() => {
  return amountTableData.reduce((sum, item) => {
    return sum + (Number(item.fileNum) || 0)
  }, 0)
})

// 初始化画布
const initCanvas = () => {
	if(processStatusOpen.value === '0') {
		ctx.value = uni.createCanvasContext('reviewUserSignaturePad')
	} else if(processStatusOpen.value === '1') {
		ctx.value = uni.createCanvasContext('recheckUserSignaturePad')
	}
  ctx.value.setStrokeStyle('#000000')
  ctx.value.setLineWidth(3)
  ctx.value.setLineCap('round')
  ctx.value.setLineJoin('round')
}

// 触摸事件处理
const onTouchStart = (e) => {
  if (readonly.value) return
  const touch = e.touches[0]
  isDrawing.value = true
  lastX.value = touch.x
  lastY.value = touch.y
}

const onTouchMove = (e) => {
  if (!isDrawing.value || readonly.value) return
  const touch = e.touches[0]
  ctx.value.beginPath()
  ctx.value.moveTo(lastX.value, lastY.value)
  ctx.value.lineTo(touch.x, touch.y)
  ctx.value.stroke()
  ctx.value.draw(true)
  lastX.value = touch.x
  lastY.value = touch.y
}

const onTouchEnd = () => {
  isDrawing.value = false
}

// 签名操作
const clearSignature = () => {
  if (readonly.value) return
  ctx.value.clearRect(0, 0, 300, 150)
  ctx.value.draw(true)
}

const saveSignature = () => {
  if (readonly.value) return
	let canvasId
	if(processStatusOpen.value === '0') {
		canvasId = 'reviewUserSignaturePad'
	} else if(processStatusOpen.value === '1') {
		canvasId = 'recheckUserSignaturePad'
	}
  uni.canvasToTempFilePath({
    canvasId: canvasId,
    success: (res) => {
      if (processStatusOpen.value === '0') {
        formData.reviewUserImg = res.tempFilePath
      } else {
        formData.recheckUserImg = res.tempFilePath
      }
      uni.showToast({ title: '签名保存成功' })
    }
  })
}

const downloadSignature = () => {
  if (!signatureData.value) return
  uni.saveImageToPhotosAlbum({
    filePath: signatureData.value,
    success: () => {
      uni.showToast({ title: '签名已保存到相册' })
    }
  })
}

// 部门选择
const openDepartmentPopup = () => {
  departmentPopup.value?.open()
}

const closeDepartmentPopup = () => {
  departmentPopup.value?.close()
}

const handleTreeChange = (allSelectedKeys, currentItem) => {
  formData.department = allSelectedKeys
  formData.departmentName = currentItem.label
}

// 加载部门树
const loadDeptTree = async () => {
  try {
    const response = await deptTreeSelect()
    if (response.code === 200) {
      function normalizeDept(list) {
        return list.map(dept => {
          dept.id = String(dept.id)
          dept.label = dept.label
          if (dept.children && dept.children.length) {
            dept.children = normalizeDept(dept.children)
          }
          return dept
        })
      }
      const mapped = normalizeDept(response.data)
      enabledDeptOptions.value = filterDisabledDept(JSON.parse(JSON.stringify(mapped)))
    }
  } catch (error) {
    console.error('加载部门树失败:', error)
  }
}

const filterDisabledDept = (deptList) => {
  return deptList.filter(dept => {
    if (dept.disabled) return false
    if (dept.children && dept.children.length) {
      dept.children = filterDisabledDept(dept.children)
    }
    return true
  })
}

// 加载用户数据
const loadAllUsers = async () => {
  try {
    const res = await listUser({ nickName: '' })
    const users = res.rows || []
    
    reimbursementUserOptions.value = users.map(user => ({
      value: user.userId,
      text: `${user.nickName}-${user.userName}`
    }))
    
    reviewUserOptions.value = [...reimbursementUserOptions.value]
    recheckUserOptions.value = [...reimbursementUserOptions.value]
  } catch (error) {
    console.error('加载用户失败:', error)
  }
}

// 加载银行选项
const loadBankOptions = async () => {
  try {
    const response = await listDeposit()
    bankOptions.value = (response.rows || []).map(bank => ({
      value: bank.bankAccount,
      text: `${bank.bankDeposit} - ${bank.bankAccount}`
    }))
  } catch (error) {
    console.error('加载银行选项失败:', error)
  }
}

// 处理银行选择变化
const handleBankChange = (accountNo) => {
  const selectedBank = bankOptions.value.find(bank => bank.value === accountNo)
  formData.bankName = selectedBank ? selectedBank.text.split(' - ')[0] : ''
}

// 加载费用类型字典
const loadCostTypeOptions = async () => {
  try {
    const params = { dictType: 'cost_type' }
    const response = await listData(params)
    if (response.code === 200) {
      costTypeOptions.value = (response.rows || []).map(item => ({
        value: item.dictValue,
        text: item.dictLabel
      }))
    }
  } catch (error) {
    console.error('加载费用类型字典失败:', error)
  }
}

// 处理会计科目选择变化
const handleSubjectChange = async (row, subjectName) => {
  row.projectName = ''
  if (!subjectName) {
    row.projectOptions = []
    return
  }
  
  try {
    const params = { dictType: subjectName }
    const response = await listData(params)
    if (response.code === 200) {
      row.projectOptions = (response.rows || []).map(item => ({
        value: item.dictValue,
        text: item.dictLabel
      }))
      projectOptionsMap.value[subjectName] = row.projectOptions
    }
  } catch (error) {
    console.error('加载项目选项失败:', error)
    row.projectOptions = []
  }
}

// 添加报销金额行
const addAmountRow = () => {
  amountTableData.push({
    obtainDate: '',
    fileName: '',
    amount: 0,
    fileNum: 0,
    fileList: [],
    remarks: '',
    fileBatchNo: ''
  })
}

// 删除报销金额行
const removeAmountRow = (index) => {
  if (amountTableData.length <= 1) {
    uni.showToast({ title: '至少保留一行数据', icon: 'none' })
    return
  }
  amountTableData.splice(index, 1)
}

// 文件管理
const openFileListDialog = (row, index) => {
  Object.assign(currentRowFile, { ...row })
  currentRowFileIndex.value = index
  filePopup.value?.open()
}

const closeFilePopup = () => {
  filePopup.value?.close()
}

const confirmFile = () => {
  if (currentRowFileIndex.value !== -1) {
    amountTableData.splice(currentRowFileIndex.value, 1, { ...currentRowFile })
  }
  closeFilePopup()
}

// 获取项目选项的方法
const getProjectOptions = async (subjectName, row) => {
  if (!subjectName) {
    row.projectOptions = []
    return
  }
  
  try {
    let params = {
      dictType: subjectName
    }
    const response = await listData(params)
    if (response.code === 200) {
      // 存储到行的projectOptions中
      row.projectOptions = response.rows.map(item => ({
        value: item.dictValue,
        text: item.dictLabel
      }))
      // 同时存储到映射表中
      projectOptionsMap.value[subjectName] = response.rows
			console.log(subjectName, row)
    }
  } catch (error) {
    console.error('加载项目选项失败:', error)
    row.projectOptions = []
  }
}

// 加载表单数据
const loadFormData = async (id) => {
  uni.showLoading({ title: '加载中' })
  
  try {
    const res = await billSummaryGet(id)
    if (res.code === 200) {
      const data = res.data
      
      // 填充表单数据
      Object.assign(formData, data)
      formData.departmentName = data.departmentName
      processStatusOpen.value = data.processStatus
      
      formData.reimbursementUser = Number(data.reimbursementUser)
      formData.reviewUser = Number(data.reviewUser)
      formData.recheckUser = Number(data.recheckUser)
      
      // 填充表格数据
      projectTableData.splice(0, projectTableData.length, ...(data.reimbursementProjectList || [
        { subjectName: '', projectName: '', totalAmount: 0, remarks: '' }
      ]))
      
      amountTableData.splice(0, amountTableData.length, ...(data.reimbursementAmountDetailsList || [
        { obtainDate: '', fileName: '', amount: 0, fileNum: 0, fileList: [], remarks: '', fileBatchNo: '' }
      ]))
      
      // 加载签名预览
      if (readonly.value) {
        signatureData.value = processStatusOpen.value === '0' ? 
          data.reviewUserImg : data.recheckUserImg
      }
      
      // 回显时加载每行的项目选项
			if (projectTableData && projectTableData.length > 0) {
				projectTableData.forEach(async row => {
					if (row.subjectName) {
						await getProjectOptions(row.subjectName, row)
					}
				})
			}
			
			if(res.data.reviewUserImg) {
				signatureDataReview.value = res.data.reviewUserImg
			}

			if(res.data.recheckUserImg) {
				signatureDataRecheck.value = res.data.recheckUserImg
			}
    }
  } catch (error) {
    console.error('加载表单数据失败:', error)
    uni.showToast({ title: '加载失败', icon: 'none' })
  } finally {
    uni.hideLoading()
  }
}

// 金额转中文大写
const amountToChinese = (money) => {
  if (!money || money === 0) return '零元整'
  
  const cnNums = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖']
  const cnIntRadice = ['', '拾', '佰', '仟']
  const cnIntUnits = ['', '万', '亿', '兆']
  const cnDecUnits = ['角', '分', '厘', '毫']
  const cnInteger = '整'
  const cnIntLast = '元'
  
  let integerNum = Math.floor(money)
  let decimalNum = Math.round((money - integerNum) * 10000)
  
  let chineseStr = ''
  
  if (integerNum === 0) {
    chineseStr += cnNums[0]
  } else {
    let integerStr = integerNum.toString()
    let zeroCount = 0
    const intLen = integerStr.length
    
    for (let i = 0; i < intLen; i++) {
      const n = parseInt(integerStr.substring(i, i + 1))
      const p = intLen - i - 1
      const q = Math.floor(p / 4)
      const m = p % 4
      
      if (n === 0) {
        zeroCount++
      } else {
        if (zeroCount > 0) {
          chineseStr += cnNums[0]
        }
        zeroCount = 0
        chineseStr += cnNums[n] + cnIntRadice[m]
      }
      
      if (m === 0 && zeroCount < 4) {
        chineseStr += cnIntUnits[q]
        zeroCount = 0
      }
    }
    chineseStr += cnIntLast
  }
  
  if (decimalNum === 0) {
    chineseStr += cnInteger
  } else {
    const decStr = decimalNum.toString().padStart(4, '0')
    let hasDecimal = false
    
    for (let i = 0; i < 4; i++) {
      const n = parseInt(decStr.substring(i, i + 1))
      if (n !== 0) {
        chineseStr += cnNums[n] + cnDecUnits[i]
        hasDecimal = true
      }
    }
    
    if (!hasDecimal) {
      chineseStr += cnInteger
    }
  }
  
  return chineseStr
    .replace(/零仟零佰零拾零/g, '零')
    .replace(/零{2,}/g, '零')
    .replace(/零(万|亿|兆|元)/g, '$1')
    .replace(/亿万/g, '亿')
}

// 表单提交
const submitForm = async () => {
  try {
    const valid = await formRef.value?.validate()
    if (!valid) return
    
    // 验证表格数据
    for (const item of projectTableData) {
      if (!item.subjectName || !item.projectName) {
        uni.showToast({ title: '请完善汇总项目清单', icon: 'none' })
        return
      }
    }
    
    for (const item of amountTableData) {
      if (!item.obtainDate || !item.fileName || !item.amount) {
        uni.showToast({ title: '请完善报销金额清单', icon: 'none' })
        return
      }
    }
    
    const params = {
      department: formData.department,
      businessTripDate: formData.businessTripDate,
      reimbursementUser: formData.reimbursementUser,
      reviewUser: formData.reviewUser,
      recheckUser: formData.recheckUser,
      bankName: formData.bankName,
      accountNo: formData.accountNo,
      reportNum: fileNumTotal.value,
      serialNumber: formData.serialNumber,
      reimbursementAmount: amountTotal.value,
      reimbursementProjectList: projectTableData,
      reimbursementAmountDetailsList: amountTableData
    }
    
    if (isApproval.value) {
      // 审批逻辑
      params.id = formData.id
      params.approvFlag = formData.approvFlag
      params.processStatus = processStatusOpen.value
      params.reviewUserNotes = formData.reviewUserNotes
      params.recheckUserNotes = formData.recheckUserNotes
      params.reviewUserImg = formData.reviewUserImg
      params.recheckUserImg = formData.recheckUserImg
      
      await billSummaryApproval(params)
    } else {
      if (formData.id) {
        // 编辑逻辑
        params.id = formData.id
        params.processStatus = formData.processStatus === '3' ? '0' : formData.processStatus
        await billSummaryEdit(params)
      } else {
        // 新增逻辑
        params.processStatus = '0'
        await billSummaryAdd(params)
      }
    }
    
    uni.showToast({ title: '提交成功' })
    handleClose()
    
  } catch (error) {
    console.error('提交失败:', error)
    uni.showToast({ title: '提交失败', icon: 'none' })
  }
}

// 关闭表单
const handleClose = () => {
  uni.navigateBack()
}

// 初始化数据
const initData = async () => {
  await loadDeptTree()
  await loadAllUsers()
  await loadBankOptions()
  await loadCostTypeOptions()
  
  if (isApproval.value) {
    nextTick(() => {
      initCanvas()
    })
  }
}

// 页面加载
onLoad((options) => {
  handle.value = options.handle || ''
  isApproval.value = options.handle === 'approve'
  readonly.value = options.handle === 'view'
  
  initData()
  
  if (options.id) {
    formData.id = options.id
    loadFormData(options.id)
  }
})
</script>

<style scoped lang="scss">
.bill-summary-form {
  min-height: 100vh;
  background-color: #f5f7fa;
}

.form-container {
}

.form-title {
  text-align: center;
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 20px;
}

.section-title {
  font-size: 16px;
  font-weight: bold;
  margin: 20px 0 10px;
  padding-left: 10px;
  border-left: 4px solid #409EFF;
}

// 表格样式
.summary-table {
  background: #fff;
  border-radius: 8px;
  overflow: auto;
  margin-bottom: 15px;
  border: 1px solid #dcdfe6;
}

.table-header,
.table-row,
.table-footer {
  display: flex;
  width: 800px;
  border-bottom: 1px solid #dcdfe6;
  
  &:last-child {
    border-bottom: none;
  }
}

.table-header {
  background-color: #f5f7fa;
  font-weight: bold;
}

.table-col {
  flex: 1;
  padding: 8px;
  min-height: 25px;
  width: 100px;
  display: flex;
  align-items: center;
  justify-content: center;
  text-align: center;
  
  &:not(:last-child) {
    border-right: 1px solid #dcdfe6;
  }
}

.table-footer {
  background-color: #ecf5ff;
  font-weight: bold;
}

.table-actions {
  text-align: center;
  margin-bottom: 20px;
}

// 签名部分
.signature-section,
.signature-preview {
  margin: 20px 0;
  padding: 15px;
  background-color: 'f9f9f9';
  border-radius: 8px;
}

.signature-pad {
  width: 100%;
  height: 150px;
  background-color: #f5f7fa;
  border: 1px dashed #dcdfe6;
  border-radius: 4px;
}

.signature-actions {
  display: flex;
  justify-content: space-between;
  margin-top: 10px;
}

.signature-image {
  width: 100%;
  border: 1px solid #eee;
  border-radius: 4px;
}

.preview-actions {
  text-align: right;
  margin-top: 10px;
}

// 文件弹窗
.file-popup {
  background: #fff;
  border-radius: 12px 12px 0 0;
  padding: 20px;
  max-height: 80vh;
}

.file-form {
  max-height: 60vh;
  overflow-y: auto;
  margin-bottom: 15px;
}

.file-uploader {
  margin-top: 10px;
}

// 操作按钮
.form-actions {
  display: flex;
  gap: 15px;
  margin-top: 30px;
}

.btn {
  border-radius: 6px;
  font-size: 14px;
  
  &.primary {
    background-color: #409EFF;
    color: #fff;
  }
  
  &.default {
    background-color: #f5f7fa;
    color: #606266;
    border: 1px solid #dcdfe6;
  }
  
  &.large {
    flex: 1;
    height: 44px;
    line-height: 44px;
  }
  
  &.small {
    padding: 4px 8px;
    font-size: 12px;
  }
}

// 多选容器
.multi-select-container {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.selected-user-tag {
  display: flex;
  align-items: center;
  background-color: #ecf5ff;
  color: #409EFF;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.add-user-btn {
  display: flex;
  align-items: center;
  background-color: #f5f7fa;
  border: 1px dashed #dcdfe6;
  padding: 4px 8px;
  border-radius: 4px;
  color: #606266;
  font-size: 12px;
}

// 弹窗样式
.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  font-weight: bold;
  font-size: 16px;
}

.popup-actions {
  display: flex;
  gap: 10px;
}

.tree-box {
  padding: 20px;
  
  .tree-box-top {
    height: 50vh;
    border: 1px solid #dcdfe6;
    border-radius: 8px;
    overflow: hidden;
  }
  
  .tree-box-btn {
    padding-top: 15px;
  }
}

:deep(.uni-forms-item__content) {
  flex-direction: column;
  align-items: flex-start;
}

:deep(.uni-forms-item__label) {
  margin-bottom: 8px;
}
</style>